package com.supermap.originTest;//package com.supermap.samplecode.layout;
//
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.supermap.data.*;
//import com.supermap.samplecode.layout.entity.SciModel;
//
//import java.io.*;
//import java.net.HttpURLConnection;
//import java.net.URL;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.util.*;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//import java.util.stream.Collectors;
//
//
//public class exportMaps {
//
//
//    //    static String sourcePath = "http://localhost:18090";
////    static String sourceToken = "_PAtPb8gWnWW22ermHhdf33slC1abLKLE1r1uV7VjieJy0c0DUMX0_uFEOizZ8StzFH0tg_Mn11MveBGsdf9-Q..";
//    static String genPath = "http://localhost:8090";
//    static String genToken = "fiAUVT1Ww8gLKFcJIv73U2sX-9AslphK5_g2aapXfSkHF_IrGQGSh4SGGGQbSL7T3FS8AzQuHDctgvtIogYCwQ..";
//    static String outPutPath = "D:/supermap/iServer/supermap-iserver-1021-22801-6464-windows-x64-deploy-usv3383/supermap-iserver-1021-22801-6464-windows-x64-deploy/webapps/iserver/output/sqlite";
//
//    /**
//     * 程序入口点
//     * The entrance of the programme.
//     */
//    public static void main(String[] args) {
//
//        //如果有参数进来，以参数为准
//        if (args.length > 0) {
//            genPath = args[0];
//            genToken = args[1];
//            outPutPath = args[2] + "/webapps/iserver/output/sqlite";
//        }
//
//
//        JSONArray jsonArray = getWorkSpaces();
//        assert jsonArray != null;
//
//        Map<String, ArrayList<JSONObject>> workSpaceMap = new HashMap<>();
//        for (int i = 0; i < jsonArray.size(); i++) {
//            // 获取当前索引的JSONObject
//            JSONObject jsonObject = jsonArray.getJSONObject(i);
//            if (workSpaceMap.get(jsonObject.get("name")) == null) {
//                workSpaceMap.put(jsonObject.get("name").toString(), new ArrayList<>(Arrays.asList(jsonObject)));
//            } else {
//                workSpaceMap.get(jsonObject.get("name")).add(jsonObject);
//            }
//        }
//
////        CloudLicense.login("13198501932", "Lyb123452");
//
//
//        try {
//            for (Map.Entry<String, ArrayList<JSONObject>> entry : workSpaceMap.entrySet()) {
//
//
//                ArrayList<JSONObject> list = entry.getValue();
//
//                List<JSONObject> mapServiceList = list.stream().filter(jsonObject -> jsonObject.get("serviceType").toString().equals("MapService")).toList();
//                if (!mapServiceList.isEmpty()) {
//
//                    System.out.println("存在地图服务");
//                    Map<String, List<JSONObject>> map = mapServiceList.stream()//.map(JSONObject::new)
//                            .collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("serviceName").split("/")[0]));
//                    for (String key : map.keySet()) {
//                        System.out.println(key);
//
//                        String requestMethod = "GET"; // 请求方式，如 GET 或 POST
//                        String url = "http://localhost:8090/iserver/services/"+key+"/rest/maps.json";
//                        URL apiUrl = new URL(url);
//                        HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
//                        connection.setRequestMethod(requestMethod);
//                        connection.setDoOutput(true);
//
//    //                         读取响应
//                        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//                        String line;
//                        StringBuffer response = new StringBuffer();
//                        while ((line = reader.readLine()) != null) {
//                            response.append(line);
//                        }
//                        reader.close();
//
//                        JSONArray ja = JSONArray.parseArray(response.toString());
//
//                        for(int i=0;i<ja.size();i++){
//                            System.out.println(ja.getJSONObject(i).getString("name"));
//                        }
//
//                        connection.disconnect();
//                    }
//
//
//                }
//
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//
////        
//
//    }
//
//
//    private static String copySMWU(String wsAddress) {
//        try {
//            File sourceFile = new File(wsAddress);
//            File destinationDir = new File(sourceFile.getParentFile().getPath() + File.separator + "new_" + sourceFile.getName());
//            int i = 0;
//            while (destinationDir.exists()) {
//                destinationDir = new File(sourceFile.getParentFile().getPath() + File.separator + "new_" + i + sourceFile.getName());
//                i++;
//            }
//            Path copied = Files.copy(Paths.get(wsAddress), Paths.get(destinationDir.getPath()));
//
//            System.out.println("File copied to: " + copied.toString());
//            return copied.toString();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    private static Datasource mapIsUseSci(String mapXML, List<Datasource> sciDataSources) {
//        for (Datasource d : sciDataSources) {
//            //<sml:DataSourceAlias>New_Line</sml:DataSourceAlias>
//            if (mapXML.contains("<sml:DataSourceAlias>" + d.getAlias() + "</sml:DataSourceAlias>"))
//                return d;
//        }
//        return null;
//    }
//
//    public static void copySci(SciModel sciModel) {
//
//        Pattern pattern = Pattern.compile("<sml:Map>([\\s\\r\\n]*)<sml:Name>(.*?)</sml:Name>");
//        Matcher matcher = pattern.matcher(sciModel.getMapXml());
//        String mapName = "";
//
//        if (matcher.find()) {
//            mapName = matcher.group(2);
//        }
//        String sciFile = sciModel.getDatasource().getConnectionInfo().getServer();
//        File file = new File(sciFile);
//        String newSciFile = sciFile.replace(file.getName(), mapName + "_ugcv.sci");
//
//        try (BufferedReader reader = new BufferedReader(new FileReader(sciFile));
//             BufferedWriter writer = new BufferedWriter(new FileWriter(newSciFile))) {
//
//            String line;
//            while ((line = reader.readLine()) != null) {
//                // 替换字符并写入输出文件
//                String replacedLine = line.replaceAll("<sml:CacheName>(.*?)</sml:CacheName>", "<sml:CacheName>" + mapName + "</sml:CacheName>");
//                writer.write(replacedLine);
//                writer.newLine();
//            }
//            System.out.println("文件复制并替换完成。");
//            sciModel.setNewSciPath(newSciFile);
//            sciModel.setUgcvName(("ugcv5-" + mapName).replaceAll("[^a-zA-Z0-9[-]\\s]", ""));
//            writer.flush();
//        } catch (Exception e) {
//            System.err.println("处理出现异常：" + e.getMessage());
//        }
//    }
//
//
//    public static JSONArray getWorkSpaces() {
//        try {
//
//
//            URL url = new URL(genPath + "/iserver/manager/workspaces.json");
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//
//            connection.setRequestMethod("GET");
//            connection.setRequestProperty("Authorization", "Bearer " + genToken);
//
//            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//            String inputLine;
//            StringBuilder response = new StringBuilder();
//
//            while ((inputLine = in.readLine()) != null) {
//                response.append(inputLine);
//            }
//            in.close();
//            connection.disconnect();
//            return JSONArray.parseArray(response.toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    public static void postUgcvProvider(SciModel sciModel) {
////        try {
////            String requestBody = "{\"name\":\"" + sciModel.getUgcvName() + "\", \"type\":\"com.supermap.services.providers.UGCV5TileProvider\", \"enabled\":true, \"config\":{\"configFile\":\"" + sciModel.getNewSciPath() + "\"}}";
////
////
////            OkHttpClient client = new OkHttpClient().newBuilder()
////                    .build();
////            MediaType mediaType = MediaType.parse("application/json");
////            RequestBody body = RequestBody.create(mediaType, requestBody);
////            Request request = new Request.Builder()
////                    .url(genPath + "/iserver/manager/providers.rjson")
////                    .method("POST", body)
////                    .addHeader("Content-Type", "application/json")
////                    .addHeader("Authorization", "Bearer " + genToken)
////                    .build();
////            Response response = client.newCall(request).execute();
////            ResponseBody responseBody = response.body();
////            if (responseBody != null) {
////                String result = responseBody.string();
////                System.out.println("Response Result:");
////                System.out.println(result);
////            }
////            System.out.println("ugcv服务提供者发布完成");
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
//
//    }
//
//    public static void postSmwuProvider(String smwuProviderName, String workSpacePath) {
//        try {
//
//            String urlString = genPath + "/iserver/manager/providers.rjson";
//
//            workSpacePath = workSpacePath.replaceAll("\\\\", "/");
//
//            String requestBody = "{\"name\":\"" + smwuProviderName + "\", \"type\":\"com.supermap.services.providers.UGCMapProvider\", \"enabled\":true, \"config\":{\"workspacePath\":\"" + workSpacePath + "\", \"mapEditable\":false, \"cacheVersion\":\"5.0\", \"preferedPNGType\":\"PNG\", \"ugcMapSettings\":[], \"multiThread\":true, \"cacheDisabled\":false, \"poolSize\":\"0\"}}";
//
//            OkHttpClient client = new OkHttpClient().newBuilder()
//                    .build();
//            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
//            RequestBody body = RequestBody.create(mediaType, requestBody);
//            Request request = new Request.Builder()
//                    .url(urlString)
//                    .method("POST", body)
//                    .addHeader("Content-Type", "application/json")
//                    .addHeader("Authorization", "Bearer " + genToken)
//                    .build();
//            Response response = client.newCall(request).execute();
//            ResponseBody responseBody = response.body();
//            if (responseBody != null) {
//                String result = responseBody.string();
//                System.out.println("Response Result:");
//                System.out.println(result);
//            }
//            System.out.println("smwu服务提供者发布完成");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
//
//
//    public static void postComponent(String mapName, String providers, String serviceType) {
//        try {
//
//            String urlString = genPath + "/iserver/manager/components.rjson";
//
//            String requestBody = "{\"name\":\"" + mapName + "\", \"alias\":\"\", \"type\":\"com.supermap.services.components.impl.MapImpl\"," +
//                    " \"providers\":\"" + providers + "\", \"interfaceNames\":\"" + serviceType + "\", " +
//                    "\"config\":{\"tileCacheConfig\":{\"outputPath\":\"D:/supermap/iServer/supermap-iserver-1021-22801-6464-windows-x64-deploy-usv3383/supermap-iserver-1021-22801-6464-windows-x64-deploy/webapps/iserver/output/sqlite\", " +
//                    "\"type\":\"SMTiles\"}, \"useCache\":false, \"useVectorTileCache\":false, \"useUTFGridCache\":false," +
//                    " \"cacheReadOnly\":false, \"utfGridCacheConfig\":{\"outputPath\":\"D:/supermap/iServer/supermap-iserver-1021-22801-6464-windows-x64-deploy-usv3383/supermap-iserver-1021-22801-6464-windows-x64-deploy/webapps/iserver/output/sqlite\", " +
//                    "\"type\":\"UTFGrid\"}, \"vectorTileCacheConfig\":{\"outputPath\":null, \"type\":\"SVTiles\"}, \"expired\":0}}: "; // 设置请求体数据
//
//            OkHttpClient client = new OkHttpClient().newBuilder()
//                    .build();
//            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
//            RequestBody body = RequestBody.create(mediaType, requestBody);
//            Request request = new Request.Builder()
//                    .url(urlString)
//                    .method("POST", body)
//                    .addHeader("Accept", "*/*")
//                    .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
//                    .addHeader("Cache-Control", "no-cache")
//                    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
//                    .addHeader("Authorization", "Bearer " + genToken)
//                    .build();
//            Response response = client.newCall(request).execute();
//            ResponseBody responseBody = response.body();
//            if (responseBody != null) {
//                String result = responseBody.string();
//                System.out.println("Response Result:");
//                System.out.println(result);
//            }
//
//            System.out.println("服务组件发布完成");
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    private static void deleteMapService(String serviceName) {
//
//        try {
//
//            String urlString = genPath + "/iserver/manager/services/" + serviceName + ".rjson";
//
//            OkHttpClient client = new OkHttpClient().newBuilder()
//                    .build();
//            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
//            RequestBody body = RequestBody.create(mediaType, "");
//            Request request = new Request.Builder()
//                    .url(urlString)
//                    .method("DELETE", body)
//                    .addHeader("Accept", "*/*")
//                    .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
//                    .addHeader("Cache-Control", "no-cache")
//                    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
//                    .addHeader("Authorization", "Bearer " + genToken)
//                    .build();
//            Response response = client.newCall(request).execute();
//            ResponseBody responseBody = response.body();
//            if (responseBody != null) {
//                String result = responseBody.string();
//                System.out.println("Response Result:");
//                System.out.println(result);
//            }
//
//            System.out.println("地图服务删除");
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }
//
//
//}
//
